package sicnu.cs.ich.ich.ranking.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sicnu.cs.ich.api.common.enums.ConfigEnum;
import sicnu.cs.ich.common.services.IConfigService;
import sicnu.cs.ich.common.services.impl.RedisService;
import sicnu.cs.ich.ich.ranking.service.IIchRankingService;

import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Optional;

/**
 * @author CaiKe
 **/
@Slf4j
@Component
@Order(value = 1)
@RequiredArgsConstructor
public class ListenerConfig implements ApplicationRunner {
    private final IConfigService configService;
    private final IIchRankingService rankingService;

    @Override
    public void run(ApplicationArguments args) {
        // 加载数据库配置文件
        final HashMap<ConfigEnum, String> configMap =
                configService.loadConfigs(ConfigEnum.ICH_HIT_MAP, ConfigEnum.ICH_HIT_ALL, ConfigEnum.ICH_HIT_TYPE);
        log.info("***** LOADING CONFIG FROM DB ... *****");
        Optional.ofNullable(configMap).ifPresent(rankingService::loadHitConfig);
        log.info("***** CONFIG LOADED. *****");
    }

    @PreDestroy
    public void destroyBeforeShutdown() {
        log.info("***** Listener On Destroy, EXPORTING CONFIG ... *****");
        configService.storeConfigs(rankingService.exportHitConfig());
        log.info("***** EXPORTED CONFIG SUCCESSFULLY . *****");
    }
}
